package com.fhz.kotlinstest.paging

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.fhz.kotlinstest.R
import com.fhz.kotlinstest.paging.MyAdapter.MyViewHolder

class UserAdapter: RecyclerView.Adapter<UserAdapter.InnerViewHolder>() {
    private val mData:MutableList<Student> = mutableListOf()
    //创建AsyncListDiffer
    private val mDiffUtil: AsyncListDiffer<Student> = AsyncListDiffer(this,UserCallback())

    class InnerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var mIdTv: TextView = itemView.findViewById(R.id.item_text)
        var image:ImageView = itemView.findViewById(R.id.item_image)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.my_item_layout,parent,false)
        return InnerViewHolder(view)
    }

    override fun onBindViewHolder(holder: InnerViewHolder, position: Int) {
        println("position---->$position")
        val userBean = mDiffUtil.currentList[position]
        holder.mIdTv.text = userBean.name

        Glide.with(holder.image.context)
            .load("https://th.bing.com/th/id/R.c6fc977ab1effc2f57c1b61ea0b4a10b?rik=xOkA2BAHTYBnfA&riu=http%3a%2f%2fpic.3gbizhi.com%2f2016%2f0619%2f20160619103137648.jpg&ehk=NulKD8j21Eu6wB9zuAYpgZ8H3J7vxPq8IiYqI%2bx%2fRy8%3d&risl=&pid=ImgRaw&r=0")
            .skipMemoryCache(true)
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .into(holder.image)

    }


    override fun onBindViewHolder(
        holder: InnerViewHolder,
        position: Int,
        payloads: MutableList<Any>
    ) {
        if (payloads.isEmpty()){
            onBindViewHolder(holder,position)
        }else{
            //更新局部数据
            val get = payloads.get(0)
            val userBean = mDiffUtil.currentList[position]
            holder.mIdTv.text = get.toString()
        }
    }


    //注意此处 返回的是AsyncListDiffer中集合大小
    override fun getItemCount():Int{
        return mDiffUtil.currentList.size
    }

    fun setData(list:MutableList<Student>){
        //使用submitList更新数据
        mDiffUtil.submitList(list)
    }
}